/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aletex.ui;

import aletex.da.UserFacade;
import aletex.entity.User;
import aletex.ui.util.JsfUtil;
import aletex.util.PasswordGenerator;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author cibervn
 */
@ManagedBean
@ViewScoped
public class AddUser implements Serializable {

    private String username;
    private String password;
    private String repassword;
    @EJB
    private UserFacade userJpa;

    /**
     * Creates a new instance of AddUser
     */
    public AddUser() {
    }

    public String save() {
        if (!password.equals(repassword)) {
            password = "";
            repassword = "";
            JsfUtil.addErrorMessageKey("AddUser_PasswordNotSame");
            return "index";
        }
        try {
            password = PasswordGenerator.hashPassword(password);
            User user = new User(username, password);
            user.setUserID(0);
            user.setCreateDate(new Date());
            user.setActive('Y');
            user.setUserType('L');
            userJpa.create(user);
            JsfUtil.addSuccessMessageKey("AddUser_Successfull");
            return "index";
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
        }
        JsfUtil.addSuccessMessageKey("AddUser_Fails");
        return "";
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
